import {Injectable} from '@angular/core';
import {HttpEvent, HttpHandler, HttpRequest, HttpResponse} from '@angular/common/http';
import {Observable, throwError} from 'rxjs';
import {catchError, map, timeout} from 'rxjs/operators';
import {Constant} from '../constant';
import {Result} from '../model/result';
import {NativeService} from './native.service';
import {CryptoService} from './crypto.service';
import {Router} from '@angular/router';

@Injectable({
    providedIn: 'root',
})
export class InterceptorService {

    constructor(private nativeService: NativeService, private crypto: CryptoService, private router: Router) {
    }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        if (req.url.includes('http://')) {
            console.log(req.url);
            console.log(req);
            return next.handle(req);
        }
        const req1 = this.previewHandle(req);
        return next.handle(req1).pipe(
            timeout(10000),
            map(event => {
                if (event instanceof HttpResponse) {
                    const res: Result = event.body;
                    if (res.code === Constant.SUCCESS_CODE) {
                        /*解密*/
                        // return new HttpResponse({body: JSON.parse(
                        // this.crypto.deCrypto(event.body.data)), status: 200});
                        return new HttpResponse({body: event.body.data, status: 200});
                    } else if (event.status === 200) {
                        throwError('');
                        if (event.body.msg === '服务器内部异常') {
                            this.router.navigateByUrl('/home/home-page/error');
                        } else if (event.body.msg === '登录信息已过期，请重新登录') {
                            this.router.navigateByUrl('/home/home-page/login-expired');
                        } else {
                            this.nativeService.showError(event.body.msg);
                        }
                    }
                }
            }),
            catchError((er) => {
                this.nativeService.showError('请求发生错误，请稍后重试');
                return throwError('');
            }),
        );
    }

    /*加解密*/
    previewHandle(req: HttpRequest<any>): HttpRequest<any> {
        const url = Constant.SERVER_URL + req.url;
        // const d = Math.ceil(Math.random() * 100000);
        // let params = req.params;
        // let body = req.body;
        // const method = req.method;
        // console.log(req);
        // let headers = req.headers.set('Content-Type', 'application/json; charset=utf-8');
        // headers = headers.append('head', String(d));
        //
        // if (method === 'GET') {
        //     const keys = params.keys();
        //     console.log(keys);
        //     for (const key of keys) {
        //         params = params.set(key, this.crypto.enCrypto(params.get(key)));
        //     }
        //     console.log(params);
        //     const queryString = params.toString();
        //     console.log(queryString);
        //     const signature = this.crypto.MD5(queryString);
        //     headers = headers.append('signature', signature);
        // }
        // if (method === 'POST') {
        //     console.log(body);
        //     console.log(JSON.stringify(body));
        //     body = this.crypto.enCrypto(JSON.stringify(body));
        //     const signature = this.crypto.MD5(body);
        //     console.log(body);
        //     console.log(signature);
        //     headers = headers.append('signature', signature);
        // }
        // return req.clone({url, params, body, headers});
        return req.clone({url});
    }
}
